from django.contrib.auth import login, logout, authenticate
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
from django.contrib.auth.models import Group
from user.models import User
# Create your views here.
# 注册的视图函数
def register_view(request):
    if request.method == 'GET':
        return render(request,'user/register.html')
    elif request.method == 'POST':
        # 接收数据
        username = request.POST.get('username')
        pwd = request.POST.get('pwd')
        pwd_cf = request.POST.get('pwd_cf')
        # 注册之前要去用户表里看看有没有用到username，
        # exists() 方法可以返回一个布尔值，存在返回True  不存在返回False
        is_use = User.objects.filter(username=username).exists()
        # filter_result = User.objects.filter(username=username)
        # if len(filter_result)>0:
        if is_use:
            url = reverse('register')
            return HttpResponse(f'<script>alert("用户名已注册");location.href="{url}"</script>')
        if username and pwd and pwd_cf:
            if pwd != pwd_cf:
                url = reverse('register')
                return HttpResponse(f'<script>alert("两次密码不一致");location.href="{url}"</script>')
            user = User.objects.create_user(username=username,password=pwd,is_staff = True)
            # 查询到组的对象
            group1,created = Group.objects.get_or_create(name = '普通员工')
            if created:
                # 先去生成权限对象
                # 将权限添加到组中
                pass
            else:
            # 将user加入到这个组中
                user.groups.add(group1)
                #记录登录状态
                login(request,user)
                url = reverse('index')
            return HttpResponse(f'<script>alert("注册成功");location.href="{url}"</script>')
        else:
            # 其中有空值
            url = reverse('register')
            return HttpResponse(f'<script>alert("用户名、密码不能为空");location.href="{url}"</script>')


# def login_view(request):
#     if request.method == 'GET':
#         return render(request, 'user/login.html')
#     elif request.method == 'POST':
#         # 接收数据
#         username = request.POST.get('username')
#         pwd = request.POST.get('pwd')
#         # 去数据库中查，有没有这个用户名username，比对密码,比对成功User 类的一个实例对象 ，返回一个空值，None
#         user = authenticate(username=username,password=pwd)
#         if user:
#             # 记录登录状态
#             login(request,user)
#
#             return redirect(reverse('index'))
#         else:
#             # 用户名或者密码不正确,
#             return redirect(reverse('login'))

class LoginView(View):
    next = ''
    def get(self,request):
        self.next = request.GET.get('next','')
        LoginView.next = self.next
        return render(request, 'user/login.html')

    def post(self,request):
        # 接收数据
        username = request.POST.get('username')
        pwd = request.POST.get('pwd')
        # 去数据库中查，有没有这个用户名username，比对密码,比对成功User 类的一个实例对象 ，返回一个空值，None
        user = authenticate(username=username,password=pwd)
        if user:
            # 记录登录状态
            login(request,user)
            url = reverse('index')
            return redirect(f'{LoginView.next}' or url)
        else:
            # 用户名或者密码不正确,
            return redirect(reverse('login'))



def userinfo_view(request,sub):
    if request.method =='GET':
        if sub == 'head':
            # 设置头像的子页面
            subhtml = 'user/set_head_img.html'
            return render(request,'user/userinfo.html',locals())
        elif sub == 'pwd':
            # 修改密码的子页面
            subhtml = 'user/edit_pwd.html'
            return render(request, 'user/userinfo.html',locals())

    else:
        # post 数据处理
        if sub == 'head':
            # 处理的是提交头像的数据
            # 特别注意：文件的接收不能使用request.POST, 而是使用request.FILES去接收
            head_img = request.FILES.get('head_img')
            url = reverse('userinfo',args=('head',))
            user = request.user
           # 保存图片 ：
            user.head_img = head_img
            user.save()
            return redirect(url)
        elif sub == 'pwd':
            # 修改密码的数据
            username = request.POST.get('username')
            old_pwd = request.POST.get('old_pwd')
            pwd = request.POST.get('pwd')
            pwd_cf = request.POST.get('pwd_cf')
            if username and old_pwd and pwd and pwd_cf:
                user = authenticate(username=username ,password=old_pwd)
                if user:
                    if pwd == pwd_cf:
                        user.set_password(pwd)
                        user.save()
                        url = reverse('login')
                        return HttpResponse(f'<script>alert("密码修改成功");location.href="{url}"</script>')
                    else:
                        url = reverse('userinfo', args=['pwd'])
                        return HttpResponse(f'<script>alert("两次密码不一致");location.href="{url}"</script>')
                else:
                    url = reverse('userinfo', args=['pwd'])
                    return HttpResponse(f'<script>alert("用户名或密码错误");location.href="{url}"</script>')
            else:
                url = reverse('userinfo', args=['pwd'])
                return HttpResponse(f'<script>alert("用户名或密码不能为空");location.href="{url}"</script>')


def logout_view(request):
    logout(request)
    return redirect(reverse('index'))